package com.iqiyi.pps.epg.core.infrastructure.log;

import com.iqiyi.pps.epg.core.infrastructure.context.UserContext;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: lishunlong
 * Date: 12-6-25
 * Time: 下午8:36
 * To change this template use File | Settings | File Templates.
 */
public class LoggerBuilder {
    private Map<String, Object> commonParams;
    private Map<String, Object> extraParams;

    public LoggerBuilder(String mod, String act, String step, Object... params) {
        commonParams = new LinkedHashMap<String, Object>();
        extraParams = new LinkedHashMap<String, Object>();
        commonParams.put("transId", UserContext.getContext().getTransId());
        commonParams.put("mod", mod);
        commonParams.put("act", act);
        commonParams.put("step", step);
        commonParams.put("user", UserContext.getContext().getName());
        commonParams.put("ip", UserContext.getContext().getIp());
        this.put(params);
    }

    public String format() {
        StringBuilder sb = new StringBuilder();
        for(String paramName: commonParams.keySet()) {
            sb.append("[");
            sb.append(paramName);
            sb.append("={}] ");
        }

        for(String paramName: extraParams.keySet()) {
            sb.append("[");
            sb.append(paramName);
            sb.append("={}] ");
        }
        return sb.toString();
    }

    public Object[] getParams() {
        List list = new ArrayList();
        list.addAll(commonParams.values());
        list.addAll(extraParams.values());
        return list.toArray(new Object[0]);
    }

    public LoggerBuilder put(Object...params) {
        //输入参数必须是成对的
        Assert.isTrue(params.length % 2 == 0);
        for(int i = 0; i < params.length; i+=2) {
            this.extraParams.put(params[i] == null?"":params[i].toString(), params[i+1] == null?"":params[i+1].toString());
        }
        return this;
    }

    public LoggerBuilder clear() {
        this.extraParams.clear();
        return this;
    }
    
    public LoggerBuilder setStep(String step) {
        this.commonParams.put("step", step);
        return this;
    }
}
